
import 'dart:convert';

import 'package:flutter_book/api/api.dart';
import 'package:flutter_book/data/model/book_chapter_model.dart';
import 'package:flutter_book/data/model/book_model.dart';
import 'package:flutter_book/locahost/book_data_file_util.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';

class SearchApi{

  static SearchApi? _api;

  static SearchApi init() {
    if(_api==null){
      _api = SearchApi();
    }
    return _api!;
  }

  //基础地址
  static const String _BASE_URL = "http://api.zhuishushenqi.com/";
  //热搜关键字
  static const String _QUERY_HOT_QUERY_KEYWORD = _BASE_URL + "book/hot-word";
  //自动匹配的关键字
  static const String _QUERY_AUTO_COMPLETE_QUERY_KEYWORD = _BASE_URL + "book/auto-complete";
  //搜索列表
  static const String _QUERY_BOOK_KEY_WORD = _BASE_URL + "book/fuzzy-search";
  //详细信息
  static const String _QUERY_BOOK_DETAIL_INFO = _BASE_URL + "book/";
  //查询资源
  static const String _QUERY_BOOK_SOURCE = _BASE_URL + "btoc?book={bookId}&view=summary";
  //书籍目录
  static const String _QUERY_BOOK_CATALOG = _BASE_URL + "atoc/{sourceid}?view=chapters";
  //小说内容
  static const String _QUERY_BOOK_CHAPTER_CONTENT =
      "http://chapterup.zhuishushenqi.com/chapter/{link}";

  ///获取热门搜索词
  Future<List<String>> getHotSearchWord()async{
    List<String> dataList=[];
    var data = await requestApi(_QUERY_HOT_QUERY_KEYWORD, Map());
    if(data!=null&&data["hotWords"]!=null&&data["hotWords"] is List){
      for (var value in data["hotWords"]) {
        dataList.add(value.toString());
      }
    }
    return dataList;
  }

  /// 搜索小说的预选词
  Future<List<String>> getSearchWord(String keyWord)async{
    List<String> dataList=[];
    Map<String,dynamic> queryParameters=Map();
    queryParameters["query"]=keyWord;
    var data = await requestApi(_QUERY_AUTO_COMPLETE_QUERY_KEYWORD, queryParameters);
    if(data!=null&&data["keywords"]!=null&&data["keywords"] is List){
      for (var value in data["keywords"]) {
        dataList.add(value.toString());
      }
    }
    return dataList;
  }


  /// 小说关键词搜索 结果
  Future<List<BookModel>> searchTargetKeyWord(String keyWord, {int start: 0, int limit: 20}) async {
    List<BookModel> bookList=[];
    Map<String,dynamic> queryParameters=Map();
    queryParameters["query"]=keyWord;
    queryParameters["start"]=start;
    queryParameters["limit"]=limit;
    var data = await requestApi(_QUERY_BOOK_KEY_WORD, queryParameters);
    "searchTargetKeyWord:${data.runtimeType}".print;
    "searchTargetKeyWord:$data".print;
    if (data!=null) {
      bookList=data["books"].map<BookModel>((e) => BookModel.fromJson(e)).toList();
    }
    return bookList;
  }


  /// 小说详情
  /// 可能会返回null
  Future<BookModel?> getBookDetailInfo(String bookId)async{
    var data = await requestApi(_QUERY_BOOK_DETAIL_INFO+bookId, Map());
    if(data!=null) {
      BookModel model = BookModel.fromJson(data);
      return model;
    }else{
      return null;
    }
  }


  /// 小说目录
  /// 可能会返回null
  Future<List<BookChapterModel>> getBookCatalogList(String bookId)async{
    List<BookChapterModel> modelList=[];
    var data = await requestApi(_QUERY_BOOK_SOURCE.replaceAll("{bookId}", bookId), Map());
    if(data!=null){
      data.toString().print;
      data.runtimeType.toString().print;
      data[0]["_id"].toString().print;
      data = await requestApi(_QUERY_BOOK_CATALOG.replaceAll("{sourceid}", data[0]["_id"]), Map());
      if(data!=null) {
        modelList = data["chapters"].map<BookChapterModel>((e) => BookChapterModel.fromJson(e, bookId)).toList();
      } else{
        "请求结果为空".print;
      }
    } else {
      "请求结果为空".print;
    }
    return modelList;
  }

  //获取章节内容
  Future getBookContent(BookChapterModel model) async {
    if (!(await BookDataFileUtil.init().getBookChapterContent(model))) {
      await _getBookContentApi(model);
    } else {
      "locahost:${model.cnContent.toString()}".dialog;
    }
  }

  //获取章节内容
  Future _getBookContentApi(BookChapterModel model) async {
    // Uri.encodeComponent(model.link??"").print;
    // Uri.decodeComponent(model.link??"").print; // To decode url
    String url = Uri.encodeComponent(model.link ?? "");
    var data = await requestApi(_QUERY_BOOK_CHAPTER_CONTENT.replaceAll("{link}", url), Map());
    if (data != null && data["chapter"] != null && data["chapter"]["cpContent"] != null) {
      model.cnContent = data["chapter"]["cpContent"];
      BookDataFileUtil.init().saveFileChapter(model);
    } else {
      model.cnContent = "没有获取到内容";
    }
    "api:${model.cnContent.toString()}".dialog;
  }


}